package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 编程式事务
    // JDBC 事务管理器
    @Autowired(required = false)
    private DataSourceTransactionManager transactionManager;
    // 定义事务属性
    // @Autowired(required=false)：表示忽略当前要注入的bean，如果有直接注入，没有跳过，不会报错。
    @Autowired(required = false)
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/del")
    public int del(Integer id) {
        if(id == null || id <= 0)
            return 0;
        // 1.开启事务
        TransactionStatus transactionStatus = null;
        int result = 0;
        try{
            transactionStatus =
                    transactionManager.getTransaction(transactionDefinition);
            // 业务操作，删除用户
            result = userService.del(id);
            System.out.println("删除：" + result);
            // 2.提交事务
            transactionManager.commit(transactionStatus); // 提交事务
        } catch (Exception e) {
            if(transactionStatus != null) {
                transactionManager.rollback(transactionStatus); // 回滚事务
            }
        }
        return result;
    }
}
